#!/bin/bash
# 随手工具箱部署脚本 - Ubuntu 24.04

# 确保脚本以root权限运行
if [ "$EUID" -ne 0 ]; then
  echo "请使用sudo运行此脚本"
  exit 1
fi

# 设置项目路径（修正为小写）
PROJECT_PATH="/projects/image-bed-url-project"
DOMAIN="work8.top"
GITEE_REPO="https://gitee.com/aylerh/image-bed-url-project.git"

echo "==== 开始部署随手工具箱 ===="

# 创建项目目录
echo "创建项目目录..."
mkdir -p $PROJECT_PATH
mkdir -p $PROJECT_PATH/logs

# 安装系统依赖
echo "安装系统依赖..."
apt update
apt install -y python3 python3-pip nginx certbot python3-certbot-nginx git python3-full python3-venv

# 克隆项目
echo "从Gitee克隆项目..."
git clone $GITEE_REPO $PROJECT_PATH/temp
if [ $? -ne 0 ]; then
  echo "克隆项目失败，请检查网络连接或仓库地址"
  exit 1
fi

# 复制项目文件
echo "复制项目文件..."
cp -r $PROJECT_PATH/temp/* $PROJECT_PATH/
rm -rf $PROJECT_PATH/temp

# 确保上传目录存在
mkdir -p $PROJECT_PATH/static/uploads

# 创建并配置虚拟环境
echo "创建Python虚拟环境..."
cd $PROJECT_PATH
python3 -m venv venv

# 安装Python依赖
echo "安装Python依赖（使用虚拟环境）..."
$PROJECT_PATH/venv/bin/pip install --upgrade pip
$PROJECT_PATH/venv/bin/pip install -r $PROJECT_PATH/requirements.txt
$PROJECT_PATH/venv/bin/pip install gunicorn uvicorn

# 确保gunicorn可执行
chmod +x $PROJECT_PATH/venv/bin/gunicorn

# 测试应用能否启动
echo "测试应用能否启动..."
cd $PROJECT_PATH
$PROJECT_PATH/venv/bin/python -c "import uvicorn; import fastapi; print('依赖检查通过')" || {
  echo "依赖检查失败，请确认requirements.txt内容正确"
  exit 1
}

# 修改server.py中的模板目录配置
echo "修改server.py中的模板目录配置..."
TEMPLATES_LINE=$(grep -n "templates = Jinja2Templates" $PROJECT_PATH/server.py | cut -d':' -f1)
if [ ! -z "$TEMPLATES_LINE" ]; then
  sed -i "${TEMPLATES_LINE}s|Jinja2Templates(directory=\"static\")|Jinja2Templates(directory=\"$PROJECT_PATH/static\")|" $PROJECT_PATH/server.py
  echo "已更新模板目录为绝对路径"
fi

# 修改server.py中的上传目录配置
echo "修改server.py中的上传目录配置..."
UPLOAD_DIR_LINE=$(grep -n "UPLOAD_DIR = " $PROJECT_PATH/server.py | cut -d':' -f1)
if [ ! -z "$UPLOAD_DIR_LINE" ]; then
  sed -i "${UPLOAD_DIR_LINE}s|UPLOAD_DIR = \".*\"|UPLOAD_DIR = \"$PROJECT_PATH/static/uploads\"|" $PROJECT_PATH/server.py
  echo "已更新上传目录为绝对路径"
fi

# 修改index.html中的成功提示
echo "检查HTML文件是否存在..."
if [ ! -f "$PROJECT_PATH/static/upload_image_url.html" ]; then
  echo "创建上传图片页面..."
  # 将原有的index.html内容复制到upload_image_url.html
  cp $PROJECT_PATH/static/index.html $PROJECT_PATH/static/upload_image_url.html
  
  # 修改upload_image_url.html的标题和添加返回按钮
  sed -i 's/<title>Work8图床<\/title>/<title>随手工具箱 - 图床工具<\/title>/' $PROJECT_PATH/static/upload_image_url.html
  sed -i 's/<body>/<body>\n    <div class="header">\n        <a href="\/" class="back-btn">← 返回<\/a>\n        <h1>图床工具<\/h1>\n    <\/div>/' $PROJECT_PATH/static/upload_image_url.html
  
  # 添加CSS样式
  sed -i 's/body {/body {\n            display: flex;\n            flex-direction: column;\n            min-height: 90vh;\n        }\n        .header {\n            display: flex;\n            align-items: center;\n            margin-bottom: 1rem;\n        }\n        .back-btn {\n            text-decoration: none;\n            color: var(--primary);\n            display: flex;\n            align-items: center;\n            margin-right: 1rem;\n            font-size: 1.2rem;\n        }\n        .content {\n            flex: 1;\n        }/' $PROJECT_PATH/static/upload_image_url.html
  
  # 添加内容包装器
  sed -i 's/<div class="upload-area"/<div class="content">\n        <div class="upload-area"/' $PROJECT_PATH/static/upload_image_url.html
  sed -i 's/<div id="result"><\/div>/<div id="result"><\/div>\n    <\/div>/' $PROJECT_PATH/static/upload_image_url.html
  
  # 创建新的index.html作为主页
  cat > $PROJECT_PATH/static/index.html << 'EOF'
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>随手工具箱</title>
    <style>
        :root { --primary: #4361ee; }
        body { 
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif; 
            max-width: 800px; 
            margin: 0 auto; 
            padding: 2rem;
            text-align: center;
            display: flex;
            flex-direction: column;
            min-height: 90vh;
        }
        h1 { 
            color: #333;
            margin-bottom: 1rem;
        }
        .content {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
        .tool-card {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 1.5rem;
            margin: 1rem 0;
            width: 80%;
            max-width: 500px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            text-decoration: none;
            color: #333;
            display: flex;
            align-items: center;
        }
        .tool-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .tool-icon {
            background: var(--primary);
            color: white;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-right: 1rem;
            font-size: 1.5rem;
        }
        .tool-details {
            text-align: left;
        }
        .tool-details h3 {
            margin: 0;
            margin-bottom: 0.5rem;
        }
        .tool-details p {
            margin: 0;
            color: #666;
            font-size: 0.9rem;
        }
        .footer {
            margin-top: 2rem;
            font-size: 12px;
            color: #666;
            padding: 10px;
        }
        .footer a {
            color: #666;
            text-decoration: none;
        }
    </style>
</head>
<body>
    <h1>随手工具箱</h1>
    <p>便捷实用的在线工具集合</p>
    
    <div class="content">
        <a href="/upload_image_url.html" class="tool-card">
            <div class="tool-icon">📷</div>
            <div class="tool-details">
                <h3>图床工具</h3>
                <p>上传图片获取可直接引用的HTTPS链接</p>
            </div>
        </a>
        
        <!-- 可以添加更多工具卡片 -->
    </div>

    <div class="footer">
        服务备案号：<a href="https://beian.miit.gov.cn" target="_blank">津ICP备2025033698号-1</a>
    </div>
</body>
</html>
EOF
fi

# 修改复制功能和成功提示
echo "修改上传成功提示方式..."
sed -i 's/alert([^)]*);/const notification = document.createElement("div"); notification.style.position = "fixed"; notification.style.bottom = "50px"; notification.style.left = "50%"; notification.style.transform = "translateX(-50%)"; notification.style.padding = "10px 20px"; notification.style.backgroundColor = "#4361ee"; notification.style.color = "white"; notification.style.borderRadius = "4px"; notification.style.zIndex = "1000"; notification.textContent = "链接已复制！"; document.body.appendChild(notification); setTimeout(() => { notification.style.opacity = "0"; notification.style.transition = "opacity 0.5s"; setTimeout(() => { document.body.removeChild(notification); }, 500); }, 2000);/' $PROJECT_PATH/static/upload_image_url.html

# 添加备案信息到网页底部
echo "添加备案信息到网页底部..."
if ! grep -q "津ICP备2025033698号-1" $PROJECT_PATH/static/upload_image_url.html; then
  sed -i 's/<\/body>/    <div class="footer" style="margin-top: 2rem; font-size: 12px; color: #666; padding: 10px; text-align: center;">\n        服务备案号：<a href="https:\/\/beian.miit.gov.cn" target="_blank" style="color: #666; text-decoration: none;">津ICP备2025033698号-1<\/a>\n    <\/div>\n<\/body>/' $PROJECT_PATH/static/upload_image_url.html
fi

# 配置Nginx
echo "配置Nginx..."
# 获取SSL证书路径
SSL_CERT="/etc/letsencrypt/live/$DOMAIN/fullchain.pem"
SSL_KEY="/etc/letsencrypt/live/$DOMAIN/privkey.pem"

# 检查SSL证书是否存在
if [ -f "$SSL_CERT" ] && [ -f "$SSL_KEY" ]; then
  echo "SSL证书已存在，配置HTTPS..."
  
  # 创建HTTPS配置
  cat > /etc/nginx/sites-available/$DOMAIN << EOF
server {
    listen 80;
    server_name $DOMAIN www.$DOMAIN;
    
    # 重定向到HTTPS
    location / {
        return 301 https://\$host\$request_uri;
    }
    
    # 用于Let's Encrypt验证
    location /.well-known/acme-challenge/ {
        root /var/www/html;
    }
}

server {
    listen 443 ssl;
    server_name $DOMAIN www.$DOMAIN;
    
    # SSL 配置
    ssl_certificate $SSL_CERT;
    ssl_certificate_key $SSL_KEY;
    
    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }

    location /static/ {
        # 使用alias时确保以/结尾
        alias $PROJECT_PATH/static/;
        expires 30d;
        add_header Cache-Control "public";
        
        # 添加跨域访问支持
        add_header Access-Control-Allow-Origin "*";
        add_header Access-Control-Allow-Methods "GET, OPTIONS";
        add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
    }

    # 限制上传文件大小
    client_max_body_size 10M;
}
EOF

else
  echo "SSL证书不存在，配置HTTP..."
  
  # 创建HTTP配置
  cat > /etc/nginx/sites-available/$DOMAIN << EOF
server {
    listen 80;
    server_name $DOMAIN www.$DOMAIN;
    
    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }

    location /static/ {
        # 使用alias时确保以/结尾
        alias $PROJECT_PATH/static/;
        expires 30d;
        add_header Cache-Control "public";
        
        # 添加跨域访问支持
        add_header Access-Control-Allow-Origin "*";
        add_header Access-Control-Allow-Methods "GET, OPTIONS";
        add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
    }

    # 用于Let's Encrypt验证
    location /.well-known/acme-challenge/ {
        root /var/www/html;
    }

    # 限制上传文件大小
    client_max_body_size 10M;
}
EOF

fi

# 添加.well-known目录
mkdir -p /var/www/html/.well-known/acme-challenge
chmod -R 755 /var/www/html

# 启用Nginx配置
ln -sf /etc/nginx/sites-available/$DOMAIN /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default  # 移除默认站点避免冲突

# 检查配置
echo "检查Nginx配置..."
nginx -t
if [ $? -ne 0 ]; then
  echo "Nginx配置有误，请检查并修复。"
  exit 1
fi

# 重启Nginx
systemctl restart nginx
if [ $? -ne 0 ]; then
  echo "重启Nginx失败，请检查服务状态。"
  systemctl status nginx
  exit 1
fi

# DNS检查工具
echo "检查域名解析..."
echo "尝试解析 $DOMAIN..."
host $DOMAIN || echo "无法解析域名，请确认DNS设置正确指向此服务器IP。"
echo "尝试解析 www.$DOMAIN..."
host www.$DOMAIN || echo "无法解析www子域名，请确认DNS设置。"

# 网络连接测试
echo "测试网络连接..."
curl -s -o /dev/null -w "HTTP状态码: %{http_code}\n" http://$DOMAIN/ || echo "无法连接到网站，请检查网络设置。"

# 配置SSL证书（如果不存在）
if [ ! -f "$SSL_CERT" ] || [ ! -f "$SSL_KEY" ]; then
  echo "配置SSL证书..."
  echo "请确认DNS已正确配置，域名 $DOMAIN 已指向此服务器"
  echo "当前服务器IP: $(curl -s ifconfig.me)"

  read -p "是否现在获取SSL证书? (y/n): " GET_SSL
  if [ "$GET_SSL" = "y" ]; then
    echo "请选择验证方式："
    echo "1. 标准HTTP验证 (需要80端口能被外网访问)"
    echo "2. DNS验证 (需要手动添加DNS TXT记录)"
    read -p "请选择 [1/2]: " SSL_METHOD
    
    if [ "$SSL_METHOD" = "1" ]; then
        certbot --nginx -d $DOMAIN -d www.$DOMAIN
    elif [ "$SSL_METHOD" = "2" ]; then
        certbot --manual --preferred-challenges dns -d $DOMAIN -d www.$DOMAIN --nginx
    else
        echo "无效选择，跳过SSL证书配置。"
    fi
    
    # 如果成功获取证书，重新配置Nginx
    if [ -f "$SSL_CERT" ] && [ -f "$SSL_KEY" ]; then
      echo "SSL证书已获取，重新配置Nginx..."
      # 递归调用此脚本重新配置
      $0
      exit 0
    fi
  else
    echo "跳过SSL证书配置，请稍后手动配置"
  fi
else
  echo "SSL证书已存在，跳过配置"
fi

# 创建systemd服务
echo "创建系统服务..."
cat > /etc/systemd/system/work8.service << EOF
[Unit]
Description=Work8 Image Hosting Service
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=$PROJECT_PATH
Environment="PATH=$PROJECT_PATH/venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
ExecStart=$PROJECT_PATH/venv/bin/gunicorn -w 4 -k uvicorn.workers.UvicornWorker server:app --bind 127.0.0.1:8000
Restart=always

[Install]
WantedBy=multi-user.target
EOF

# 设置项目目录权限
echo "设置目录权限..."
find $PROJECT_PATH/static -type d -exec chmod 755 {} \;
find $PROJECT_PATH/static -type f -exec chmod 644 {} \;
chown -R www-data:www-data $PROJECT_PATH
chmod -R 755 $PROJECT_PATH

# 创建测试文件验证上传目录
echo "创建测试文件..."
date_path=$(date +"%Y/%m")
sudo -u www-data mkdir -p $PROJECT_PATH/static/uploads/$date_path
sudo -u www-data touch $PROJECT_PATH/static/uploads/$date_path/test_file.txt
sudo -u www-data echo "测试内容 $(date)" > $PROJECT_PATH/static/uploads/$date_path/test_file.txt
echo "测试文件路径: $PROJECT_PATH/static/uploads/$date_path/test_file.txt"

# 尝试直接启动应用（用于测试）
echo "测试直接启动应用..."
cd $PROJECT_PATH
sudo -u www-data $PROJECT_PATH/venv/bin/python -c "import fastapi; import uvicorn; print('应用依赖检查通过')" || {
  echo "应用依赖检查失败，可能需要调整依赖配置"
  exit 1
}

# 启用并启动服务
echo "启用服务..."
systemctl daemon-reload
systemctl enable work8

# 先停止服务（如果在运行）
systemctl stop work8

echo "启动服务..."
systemctl start work8

# 检查服务状态
echo "检查服务状态..."
systemctl status work8 --no-pager

# 如果服务启动失败，尝试直接运行以查看错误
if ! systemctl is-active --quiet work8; then
  echo "服务启动失败，尝试直接运行以诊断问题..."
  cd $PROJECT_PATH
  sudo -u www-data $PROJECT_PATH/venv/bin/gunicorn -w 4 -k uvicorn.workers.UvicornWorker server:app --bind 127.0.0.1:8000 --log-level debug &
  sleep 5
  kill $!
fi

echo "==== 随手工具箱部署完成 ===="
echo "访问 https://$DOMAIN 或 http://$DOMAIN 测试您的随手工具箱服务"
echo "图床工具可通过 https://$DOMAIN/upload_image_url.html 直接访问"
echo ""
echo "测试上传目录访问: https://$DOMAIN/static/uploads/$date_path/test_file.txt"
echo ""
echo "如果遇到问题，请检查："
echo "1. 服务状态：systemctl status work8"
echo "2. Nginx状态：systemctl status nginx"
echo "3. 服务日志：journalctl -u work8 -n 50"
echo "4. Nginx日志：tail -f /var/log/nginx/error.log"
echo ""
echo "如果服务无法启动，可以尝试直接运行："
echo "cd $PROJECT_PATH && sudo -u www-data $PROJECT_PATH/venv/bin/gunicorn -w 4 -k uvicorn.workers.UvicornWorker server:app --bind 127.0.0.1:8000 --log-level debug" 